package edu.ptu.shortlink.admin.common.biz.user;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import edu.ptu.shortlink.admin.common.convention.exception.ClientException;
import edu.ptu.shortlink.admin.common.convention.result.Results;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;
import java.io.PipedWriter;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;

import static edu.ptu.shortlink.admin.common.enums.UserErrorCodeEnums.USER_TOKEN_FAIL;

/**
 * @BelongsProject: shortlink
 * @BelongsPackage: edu.ptu.shortlink.admin.common.biz.user
 * @Author: HYJ
 * @CreateTime: 2025-04-26  01:04
 * @Description: 用户信息过滤器
 * @Version: 1.0
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {

        // 如果是OPTIONS请求，直接放行
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String username = httpServletRequest.getHeader("username");

        if (StrUtil.isNotBlank(username)) {
            // 从请求头中获取用户信息
            String userId = httpServletRequest.getHeader("userId");
            String realName = httpServletRequest.getHeader("realName");

            // 将用户信息存入ThreadLocal
            UserInfoDTO userInfoDTO = new UserInfoDTO(userId, username, realName);
            UserContext.setUser(userInfoDTO);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }
}

